﻿//利用lock 解决多线程同时访问同一个文件资源冲突被占用的问题
for (int i = 0; i < 10; i++) {
    Com.RunTask(i);
}
Console.ReadLine();

public class Com
{
    static readonly object _lockObj=new object();
    public static Task RunTask(int i)
    {
        return Task.Run(() => {
            string txt = $"这是第{i}次的文本";
            Console.WriteLine(txt);
            WriteTxt(txt);
        });
    }

    public static void WriteTxt(string txt)
    {
        lock (_lockObj)
        {
            using (StreamWriter sw = new StreamWriter("test.txt", true))
            {
                sw.WriteLine(DateTime.Now);
                sw.WriteLine(txt);
                sw.Close();
            }
        }
    }
}

